home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip0493.zip / BITSTRNG.C < prev    next >
C/C++ Source or Header  |  1993-04-05  |  2KB  |  60 lines

  1. /*
  2. ** bitstring(): print bit pattern of bytes formatted to string.
  3. **
  4. ** By J. Blauth, Sept. 1992. Hereby placed into the public domain.
  5. **
  6. ** byze:    value to transform to bitstring.
  7. ** biz:     count of bits to be shown (counted from lowest bit, can be any
  8. **          even or odd number).
  9. ** strwid:  total width the string shall have. Since between every 4 bits a
  10. **          blank (0x20) is inserted (not added after lowest bit), width of
  11. **          bitformat only is (biz+(biz/4-1)). Bits are printed right aligned,
  12. **          positions from highest bit to start of string filled with blanks.
  13. **          If value of strwid smaller than space needed to print all bits,
  14. **          strwid is ignored (e.g.:
  15. **                bitstr(s,b,16,5) results in 19 chars +'\0').
  16. **
  17. **   EXAMPLE:
  18. **   for (j = 1; j <= 16; j++) { bitstring(s, j, j, 16); puts(s); }
  19. **       1:                1
  20. **       2:               10
  21. **       3:              011
  22. **       d: 0 0000 0000 1101
  23. **       e: 00 0000 0000 1110
  24. **       f: 000 0000 0000 1111
  25. */
  26.  
  27. void bitstring(char *str, long byze, int biz, int strwid)
  28. {
  29.       int i, j;
  30.  
  31.       j = strwid - (biz + (biz >> 2)- (biz % 4 ? 0 : 1));
  32.       for (i = 0; i < j; i++)
  33.             *str++ = ' ';
  34.       while (--biz >= 0)
  35.       {
  36.             *str++ = ((byze >> biz) & 1) + '0';
  37.             if (!(biz % 4) && biz)
  38.                   *str++ = ' ';
  39.       }
  40.       *str = '\0';
  41. }
  42.  
  43. #ifdef TEST
  44.  
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47.  
  48. int main(void)
  49. {
  50.       char s[80]; long j;
  51.       for (j = 1L; j <= 16L; j++)
  52.       {
  53.             bitstring(s, (long)j, (int)j, 16);
  54.             printf("%2ld: %s\n", j, s);
  55.       }
  56.       return EXIT_SUCCESS;
  57. }
  58.  
  59. #endif
  60.